package com.vzaar.transport.httpclient3;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.net.ssl.SSLSocket;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory;

/**
 * SSL socket factory to override TLS problem with either nginx 0.6.xx 
 * or haproxy.
 * 
 * @author Marc G. Smith
 */
public class Ssl3OnlyProtocolFactory implements ProtocolSocketFactory {

	///////////////////////////////////////////////////////////////////////////
	// Private Members ////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////

	private SSLProtocolSocketFactory delegate = 
		new SSLProtocolSocketFactory();
	
	///////////////////////////////////////////////////////////////////////////
	// Public Methods /////////////////////////////////////////////////////////
	///////////////////////////////////////////////////////////////////////////

	public Socket createSocket(String host, int port) 
		throws IOException, UnknownHostException 
	{
		SSLSocket sslSocket = (SSLSocket) delegate.createSocket(host, port);
		sslSocket.setEnabledProtocols(new String[] { "SSLv3" });
		return sslSocket;
	}

	///////////////////////////////////////////////////////////////////////////

	public Socket createSocket(
		String host, int port, InetAddress clientHost, int clientPort)
		throws IOException, UnknownHostException 
	{
		SSLSocket sslSocket = (SSLSocket) delegate.createSocket(
			host, port, clientHost, clientPort);
		sslSocket.setEnabledProtocols(new String[] { "SSLv3" });
		return sslSocket;
	}

	///////////////////////////////////////////////////////////////////////////

	public Socket createSocket(
			String host, int port, InetAddress clientHost, int clientPort, 
		HttpConnectionParams params) 
		throws IOException,	UnknownHostException, ConnectTimeoutException 
	{
		SSLSocket sslSocket = (SSLSocket) delegate.createSocket(
			host, port, clientHost, clientPort, params);
		sslSocket.setEnabledProtocols(new String[] { "SSLv3" });
		return sslSocket;
	}

	///////////////////////////////////////////////////////////////////////////
}
